/**
 * Created by hanj on 2022/3/13 16:49
 */
package com.example.demo;

import com.example.demo.util.PackagingExcel;
import net.lingala.zip4j.exception.ZipException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.concurrent.*;

/**
 * 异步多线程
 * <p>
 * 在同一个线程池中执行多个任务
 * 确保线程池中所有的任务执行完成
 *
 * 实现多文件同时下载
 */
@RestController
@RequestMapping("/test/")
public class ThreadTest {

    @PostMapping("export")
    public void export(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //压缩文件夹地址
        String realPath = session.getServletContext().getRealPath("template/");
        String zipName = "downZip.zip";
        // 清空response
        response.reset();

        ExecutorService pool = Executors.newFixedThreadPool(3);
        CountDownLatch latch = new CountDownLatch(3);
        //启动线程1
        Thread1 thread1 = new Thread1(latch, realPath,response);
        pool.execute(thread1);
        //启动线程2
        Thread2 thread2 = new Thread2(latch);
        pool.execute(thread2);
        //启动线程3
        Thread3 thread3 = new Thread3(latch);
        pool.execute(thread3);
        latch.await();
        pool.shutdown();

        //打包
        PackagingExcel.toZipFile(realPath + zipName, realPath, null);

        // 下载压缩文件
        File fileZip = new File(realPath + zipName);
        PackagingExcel.downloadFile(fileZip, response, true, request);
    }

}
